import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_country_website/model/New.dart';
import 'package:get/get.dart';

import '../conf/configure.dart';
import 'package:http/http.dart' as http;

import 'new_detail_page.dart';

class NewsPage extends StatefulWidget {
  const NewsPage({Key? key}) : super(key: key);

  @override
  State<NewsPage> createState() => _NewsPageState();
}

class _NewsPageState extends State<NewsPage> {

  List news = [];

  @override
  void initState() {
    getNews(1);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('消息'),
        centerTitle: true,
        elevation: 0,
      ),
      body: news.isNotEmpty ? content() : SizedBox(),
    );
  }

  Widget content() {
    return Container(
      // padding: EdgeInsets.symmetric(horizontal: 15),
      child: ListView.separated(
        shrinkWrap: true,
        itemCount: news.length,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () {
              Get.to(() => NewDetailPage(detail: news[index]));
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 15),
              height: 60,
              child: Row(
                children: [
                  Image.asset('assets/message.png', width: 30),
                  SizedBox(width: 10),
                  Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          Text(news[index].title, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis),
                          Text(news[index].content, maxLines: 1, overflow: TextOverflow.ellipsis,)
                        ],
                      )
                  ),
                  Icon(Icons.navigate_next_rounded, size: 30)
                ],
              ),
            ),
          );
        },
        separatorBuilder: (BuildContext context, int index) {
          return Container(
            height: 1,
            color: Colors.grey.withOpacity(0.2),
          );
        },
      ),
    );
  }

  void getNews(int page) async {
    String url = 'http://' + Config.IP + ':' + Config.PORT + '/?action=getNews&page=$page';

    var res = await http.get(Uri.parse(url));
    String body = res.body;
    debugPrint("body: $body");

    Map bodyMap = jsonDecode(body);
    List item = bodyMap['items'];
    item.forEach((element) {
      news.add(New.fromJson(element));
    });
    setState(() {});
  }
}
